<?php

namespace addons\sum\controller;

use addons\sum\controller\Base;
use addons\sum\model\UserWalletLog;
use app\common\model\CommissionLog;
use think\Db;
use app\common\library\Sms;
use fast\Random;
use think\Log;
use think\Validate;
use addons\sum\library\Wechat;
use addons\sum\model\UserOauth;
use addons\sum\model\User as UserModel;

/**
 * 会员接口
 */
class User extends Base
{
    protected $noNeedLogin = ['accountLogin', 'smsLogin', 'register', 'forgotPwd', 'wxMiniProgramOauth', 'getWxMiniProgramSessionKey', 'wxOfficialAccountOauth', 'wxOfficialAccountBaseLogin', 'wxOpenPlatformOauth', 'appleIdOauth', 'logout', 'check_user'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        return parent::_initialize();
    }
    public function check_user(){
        $to_user_num = $this->request->post('to_user_num');
        $to_user=UserModel::field("id,oil_num,mobile")->where('oil_num',$to_user_num)->whereOr('mobile',$to_user_num)->find();
        if(!$to_user){
            $this->success('没有该用户',$to_user_num);
        }else{
            $this->success('操作成功',$to_user);
        }
    }
    /**
     * 我的团队
     *
     * @return void
     */
    public function team()
    {
        $params = $this->request->get();
        extract($params);
        $this->auth->setAllowFields(['id', 'username', 'nickname', 'mobile', 'avatar', 'score', 'money', 'commission', 'pid','layer']);
        $user = $this->auth->getUserinfo();

        if (isset($id)) {
            // 查询 id 是否是当前用户的下级
            $childUser = UserModel::where('pid', $user['id'])->where('id', $id)->count();
            if (!$childUser) {
                $this->error('用户不存在');
            }
        } else {
            $id = $user['id'];
        }

        if(!isset($sort)){
            $sort='createtime';
        }
        if(!isset($order)){
            $order='asc';
        }

        $fields = 'id,nickname,avatar,pid,createtime,oil_num,litre,layer,did';
        $first_ids=UserModel::where('pid', $user['id'])->column('id');
        if(empty($first_ids)){
            $first_ids=[-1];
        }
        $teams = UserModel::where('id','in', $first_ids)
            ->whereOr('pid','in', $first_ids)
            ->field($fields)
            ->order($sort,$order)
            ->paginate($per_page ?? 10);
        $teams->each(function ($item)use($user){
            $item->relative_layer=$item->layer - $user['layer'];//相对层数级别
            $item->relative_commission=UserWalletLog::where('user_id',$user['id'])->where('related_user_id',$item['id'])->where('type','commission_income')->where('wallet_type','commission')->sum('wallet');
        });

        $parentUser = null;
        if ($user['pid']) {
            $parentUser = UserModel::where('id', $user['pid'])->field('id,nickname,avatar')->find();
        }
        $this->success('我的团队', [
            'teams' => $teams,
            'user' => $user,
            'parent_user' => $parentUser
        ]);
    }
    //需要把自己放入到团队中
    public function teamwithself()
    {
        $params = $this->request->get();
        extract($params);
        $this->auth->setAllowFields(['id', 'username', 'nickname', 'mobile', 'avatar', 'score', 'money', 'pid','self_times']);
        $user = $this->auth->getUserinfo();

//        $fields = 'id,avatar,use_times';
//        $teams = UserModel::where('pid', $user['id'])
//            ->field($fields)
//            ->order('createtime', 'asc')
//            ->where('use_times','>',0)
//            ->limit(20)
//            ->select();
        //2024-05-09 修改为只有自己的次数
        $selfs=[];
        $selfdata['id']=$user['id'];
        $extend = $this->getUserDefaultFields();
        $selfdata['avatar']=cdnurl($extend['avatar'],true);
        for ($i=0;$i<$user['self_times'];$i++){
            $selfs[]=$selfdata;
        }
        $this->success('我的团队', [
            'teams' => $selfs,
        ]);
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $auth = \app\common\library\Auth::instance();
        $auth->setAllowFields(['id', 'username', 'nickname', 'mobile', 'avatar', 'score', 'birthday', 'money', 'group', 'group_id', 'verification', 'child_user_count', 'child_user_count_1', 'child_user_count_2', 'total_consume','money_store','oil_num','self_times','pid','did','is_team_leader']);
        $data = $auth->getUserinfo();
        $data['avatar'] = $data['avatar'] ? cdnurl($data['avatar'], true) : '';
        if (!isset($data['group'])) {
            $data['group'] = \addons\sum\model\UserGroup::get($data['group_id']);
        }
        // 处理订单数据
        $order_count=Db::name('oil_order')->where('user_id',$data['id'])->where('status',2)->count();
        $order_money=Db::name('oil_order')->where('user_id',$data['id'])->where('status',2)->sum('total_fee');
        $order_discount=Db::name('oil_order')->where('user_id',$data['id'])->where('status',2)->sum('discount_fee');

        //可开票车队燃油费-充值金额
        $rechareg_invoice_money=Db::name('sum_trade_order')->where('user_id',$data['id'])->where('status','in',['paid','completed'])->where('invoice_status',0)->sum('pay_fee');

        //可开票车队燃油费
//        $goods_invoice_money=Db::name('oil_order')->where('user_id',$data['id'])->where('status',2)->where('goods_invoice_status',0)->sum('total_amount');
//        //可开票车队服务费
//        $service_invoice_money=Db::name('oil_order')->where('user_id',$data['id'])->where('status',2)->where('service_invoice_status',0)->sum('dispatch_amount');
//        $invoice_money=$goods_invoice_money+$service_invoice_money;
        $invoice_money=$rechareg_invoice_money;
        $data['order_count']=$order_count;//累计消费次数
        $data['order_money']=$order_money;//累计消费金额
        $data['order_discount']=$order_discount;//累计折扣
        $data['invoice_money']=$invoice_money;//当前可开发票金额

        // 上级用户信息
        $parentUser = null;
        if ($data['pid']) {
            $parentUser = UserModel::where('id', $data['pid'])->field('id,nickname,avatar,mobile,oil_num')->find();
        }
        $data['parent_user']=$parentUser;//当前可开发票金额
        $this->success('用户信息', $data);
    }


    /**
     * 获取用户数据
     *
     * @return void
     */
    public function userData()
    {
        $user = $this->auth->getUserinfo();
        // 订单数量
        $data['order_num'] = \addons\oil\model\Order::statusNum();

        $this->success('用户数据', $data);
    }
    public function recom_record()
    {
        if ($this->request->isPost()){
            $uinfo = $this->auth->getUser();
            $model = Db::name('user');
            $infos = $model
                ->where('tid',$uinfo['id'])
                ->field('id,nickname,avatar,createtime')
                ->order('id','desc')
                ->paginate(15);
//            $data = $infos->all();
            foreach ($infos as $index => &$item) {
                $item['avatar'] = cdnurl($item['avatar'],true);
                $infos[$index] = $item;
            }
//            $sql = \db()->getLastSql();
            $this->success('分享纪录', $infos);
        }
    }
    /**
     * 1.账号登录
     *
     * @param string $account 账号
     * @param string $password 密码
     */
    public function accountLogin()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['token' => $this->auth->getToken()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 2.短信登录
     *
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function smsLogin()
    {
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$mobile || !$code) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $code, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['token' => $this->auth->getToken()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 3.注册会员
     *
     * @param string $mobile 手机号
     * @param string $password 密码
     * @param string $code 验证码
     */
    public function register()
    {
        $username = $this->request->post('mobile');
        $password = $this->request->post('password');
        $email = $this->request->post('mobile') . '@' . request()->host();

        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$password) {
            $this->error(__('请填写密码')); //TODO:密码规则校验
        }
        if (strlen($password) < 6 || strlen($password) > 16) {
            $this->error(__('密码长度 6-16 位')); //TODO:密码规则校验
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('邮箱填写错误'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号填写错误'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $extend = $this->getUserDefaultFields();
        $ret = $this->auth->register($username, $password, $email, $mobile, $extend);
        if ($ret) {
            $user = $this->auth->getUser();
            $user->nickname = $user->nickname . $user->id;
            $verification = $user->verification;
            $verification->mobile = 1;
            $user->verification = $verification;
            $user->save();
            $data = ['token' => $this->auth->getToken()];
            $this->success(__('注册成功'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 4.忘记密码
     *
     * @param string $mobile 手机号
     * @param string $password 新密码
     * @param string $code 验证码
     */
    public function forgotPwd()
    {
        $mobile = $this->request->post("mobile");
        $newpassword = $this->request->post("password");
        $captcha = $this->request->post("code");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (strlen($newpassword) < 6 || strlen($newpassword) > 16) {
            $this->error(__('密码长度 6-16 位')); //TODO:密码规则校验
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            $this->error(__('User not found'));
        }
        $ret = Sms::check($mobile, $captcha, 'resetpwd');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        Sms::flush($mobile, 'resetpwd');
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 5.绑定手机号
     *
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function bindMobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('code');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success(__('Mobile is binded'));
    }


    /**
     * 6.修改密码
     *
     * @param string $oldpassword 手机号
     * @param string $newpassword 验证码
     */
    public function changePwd()
    {
        $user = $this->auth->getUser();

        $oldpassword = $this->request->post("oldpassword");
        $newpassword = $this->request->post("newpassword");

        if (!$newpassword || !$oldpassword) {
            $this->error(__('Invalid parameters'));
        }
        if (strlen($newpassword) < 6 || strlen($newpassword) > 16) {
            $this->error(__('密码长度 6-16 位')); //TODO:密码规则校验
        }

        $ret = $this->auth->changepwd($newpassword, $oldpassword);

        if ($ret) {
            $this->auth->direct($user->id);
            $data = ['userinfo' => $this->auth->getUserinfo()];

            $this->success(__('Change password successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 获取微信小程序session_key
     *
     * @param string  $code       加密code
     * @param boolean $autoLogin  是否自动登录(需已注册会员)
     */
    public function getWxMiniProgramSessionKey()
    {
        $post = $this->request->post();
        $autoLogin = $post['autoLogin'];
        $wechat = new Wechat('wxMiniProgram');
        $decryptSession = $wechat->code($post['code']);
        if (!isset($decryptSession['session_key'])) {
            $this->error('未获取session_key,请重启应用');
        }
        \think\Cache::set($decryptSession['session_key'], $decryptSession, 24 * 3600 * 31); // 强制31天过期
        $userOauth = UserOauth::get([
            'provider' => 'Wechat',
            'platform' => 'wxMiniProgram',
            'openid' => $decryptSession['openid'],
            'user_id' => ['neq', 0]
        ]);
        if ($userOauth) {
            $userOauth->save(['session_key' => $decryptSession['session_key']]);
        }
        if ($autoLogin && $userOauth) {
            $ret = $this->auth->direct($userOauth->user_id);
            if ($ret) {
                $token = $this->auth->getToken();
                $this->success(__('Logged in successful'), ['token' => $token, 'session_key' => $decryptSession['session_key'], 'openid' => $decryptSession['openid']]);
            } else {
                $this->error($this->auth->getError());
            }
        }

        $this->success('', $decryptSession);
    }
    /**
     * 微信小程序登录
     *
     * @param string  $session_key      session_key
     * @param string  $signature        校验签名
     * @param string  $iv               解密向量
     * @param string  $encryptedData    需解密完整用户信息
     * @param boolean $refresh          重新获取或刷新最新的用户信息 (用户头像失效或微信客户端修改昵称等情况)
     */
    public function wxMiniProgramOauth()
    {
        $post = $this->request->post();
        $token = Db::transaction(function () use ($post) {
            $invitecode=$post['invitecode']??'';//邀请代码
            try {
                $wechat = new Wechat('wxMiniProgram');
                $decryptSession = \think\Cache::get($post['session_key']);
                if (!$decryptSession || !isset($decryptSession['openid'])) {
                    Log::write($decryptSession,'error');
                    throw \Exception('未获取到登录态,请重试');
                }
                $decryptUserInfo = $wechat->decryptData($post['session_key'], $post['iv'], $post['encryptedData']); // 客户端传值数据都不可信，需服务端解密用户信息
                $decryptUserInfo = array_merge($decryptUserInfo, $decryptSession);
                //组装decryptData
                $decryptData = array_change_key_case($decryptUserInfo, CASE_LOWER);
//                Log::info(['decryptData'=>$decryptData]);
//                Log::info(['post'=>$post]);
                if (empty($decryptData['openid'])) {
                    throw \Exception('code错误,请重试');
                }
//                $decryptData['headimgurl'] = $decryptData['avatarurl'];
//                $decryptData['sex'] = $decryptData['gender'];
                $decryptData['session_key'] = $post['session_key'];
                return $this->oauthLoginOrRegisterOrBindOrRefresh($post['event'], $decryptData, 'wxMiniProgram', 'Wechat',0,$invitecode);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
        });

        if ($token) {
            $this->success(__('Logged in successful'), ['token' => $token]);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 微信APP登录
     *
     * @param string $authResult 授权信息
     */
    public function wxOpenPlatformOauth()
    {
        $post = $this->request->post();

        $token = Db::transaction(function () use ($post) {
            try {
                //组装decryptData
                $authResult = $post['authResult'];
                $res = \fast\Http::get('https://api.weixin.qq.com/sns/userinfo?access_token=' . $authResult['access_token'] . '&openid=' . $authResult['openid']);
                $userInfo = json_decode($res, true);
                if (isset($userInfo['errmsg'])) {
                    throw \Exception($userInfo['errmsg']);
                }
                $decryptData = array_merge($userInfo, $authResult);
                return $this->oauthLoginOrRegisterOrBindOrRefresh($post['event'], $decryptData, 'App', 'Wechat');
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
        });

        if ($token) {
            $this->success(__('Logged in successful'), ['token' => $token]);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 微信公众号登录、更新信息、绑定(授权页 非api)
     *
     * @param string $code 加密code
     */
    public function wxOfficialAccountOauth()
    {
        $token = '';
        $params = $this->request->get();

        $payload = json_decode(htmlspecialchars_decode($params['payload']), true);
        // 解析前端主机
        if ($payload['event'] !== 'login' && $payload['token'] !== '') {
            $this->auth->init($payload['token']);
        }

        $wechat = new Wechat('wxOfficialAccount');
        $oauth = $wechat->oauth();
        $decryptData = $oauth->user()->getOriginal();
        $token = Db::transaction(function () use ($payload, $decryptData) {
            try {
                $token = $this->oauthLoginOrRegisterOrBindOrRefresh($payload['event'], $decryptData, 'wxOfficialAccount', 'Wechat');
                return $token;
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
        });
        // 跳转回前端
        if ($token) {
            header('Location: ' . $payload['host']  . 'pages/public/loading/?token=' . $token);
        } else {
            header('Location: ' . $payload['host']);
        }
        exit;
    }

    /**
     * 苹果ID授权
     *
     * @param string $authResult 授权信息
     * @param string $userInfo 用户信息
     */
    public function appleIdOauth()
    {
        $post = $this->request->post();
        $userInfo = $post['userInfo'];
        $token = '';
        $platform = request()->header('platform');

        try {
            \think\Loader::addNamespace('AppleSignIn', ADDON_PATH . 'shopro' . DS . 'library' . DS . 'apple-signin' . DS);
            $identityToken = $userInfo['identityToken'];
            $clientUser = $userInfo['openId'];
            $appleSignInPayload = \AppleSignIn\ASDecoder::getAppleSignInPayload($identityToken);
            $isValid = $appleSignInPayload->verifyUser($clientUser);
            if ($isValid) {
                $nickname = '';
                $headimgurl = '';
                if (isset($userInfo['fullName']['familyName'])) {
                    $nickname = $userInfo['fullName']['familyName'] . ' ' . $userInfo['fullName']['giveName'];
                } else {
                    $nickname = '';
                }
                $decryptData = [
                    'openid' => $userInfo['openId'],
                    'nickname' => $nickname,
                    'access_token' => $userInfo['authorizationCode'],
                    'headimgurl' => $headimgurl
                ];
                $token = $this->oauthLoginOrRegisterOrBindOrRefresh($post['event'], $decryptData, $platform, 'Apple');
            }
        } catch (\Exception $e) {
            $this->error('登录失败:' . $e->getMessage());
        }

        if ($token) {
            $this->success(__('Logged in successful'), ['token' => $token]);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 微信公众号静默登录
     *
     * @param string $code 加密code
     */
    public function wxOfficialAccountBaseLogin()
    {
        $wechat = new Wechat('wxOfficialAccount');
        $oauth = $wechat->oauth();
        $oUrl = input('get.state');
        $url = explode('/', $oUrl);
        $decryptData = $oauth->user()->getOriginal();
        if ($decryptData) {
            header('Location:' . $oUrl . '&openid=' . $decryptData['openid']);
        } else {
            $this->error('未获取到OPENID');
        }
    }

    /**
     * 第三方登录或自动注册或绑定
     *
     * @param string  $event        事件:login=登录, refresh=更新账号授权信息, bind=绑定第三方授权
     * @param array   $decryptData  解密参数
     * @param string  $platform     平台名称
     * @param string  $provider     厂商名称
     * @param int     $keeptime     有效时长
     * @return string $token        返回用户token
     */
    private function oauthLoginOrRegisterOrBindOrRefresh($event, $decryptData, $platform, $provider, $keeptime = 0,$invitecode=null)
    {
        $oauthData = $decryptData;
        $oauthData = array_merge($oauthData, [
            'provider' => $provider,
            'platform' => $platform,

        ]);
        if ($platform === 'wxMiniProgram' || $platform === 'App') {
            $oauthData['expire_in'] = 7200;
            $oauthData['expiretime'] = time() + 7200;
        }
        $userOauth = UserOauth::where(['openid' => $decryptData['openid'], 'user_id' => ['neq', 0]])->where('platform', $platform)->where('provider', $provider)->lock(true)->find();
//        Log::info(['userOauth'=>$userOauth]);
        switch ($event) {
            case 'login':               // 登录(自动注册)
                if (!$userOauth) {      // 没有找到第三方登录信息 创建新用户
                    //默认创建新用户
                    $user_id = 0;
                    $createNewUser = true;
                    $oauthData['logintime'] = time();
                    $oauthData['logincount'] = 1;
                    // 判断是否有unionid 并且已存在oauth数据中
                    if (isset($oauthData['unionid'])) {
                        //存在同厂商信息，添加oauthData数据，合并用户
                        $userUnionOauth = UserOauth::get(['unionid' => $oauthData['unionid'], 'provider' => $provider, 'user_id' => ['neq', 0]]);
                        if ($userUnionOauth) {
                            $existUser = $this->auth->direct($userUnionOauth->user_id);
                            if ($existUser) {
                                $createNewUser = false;
                            }
                        }
                    }

                    // 创建空用户
                    if ($createNewUser) {
                        $pid=0;
                        if($invitecode){
                            $invite_field='id';//邀请码字段-可扩展为手机号，邮箱，邀请码等
                            $invite_map[$invite_field]=$invitecode;
                            $invite_user=UserModel::where($invite_map)->find();
                            if($invite_user){
                                $pid=$invite_user['id'];
                            }
                        }
//                        Log::info(['pid'=>$pid]);
                        $username = Random::alnum(20);
                        $password = '';
                        $domain = request()->host();
                        $extend = $this->getUserDefaultFields();
//                        Log::info(['extend'=>$extend]);
                        $extend['nickname'] = isset($oauthData['nickname']) ? $oauthData['nickname'] : $extend['nickname'];
                        $extend['avatar'] = isset($oauthData['headimgurl']) ? $oauthData['headimgurl'] : $extend['avatar'];
                        if(isset($oauthData['phonenumber'])){
                            $mobile=$oauthData['phonenumber'];
                        }else{
                            $mobile='';
                        }
                        $extend['pid']=$pid;
//                        Log::info(['oauthData'=>$oauthData]);
                        $this->auth->register($username, $password, $username . '@' . $domain, $mobile, $extend);
                        if (!isset($oauthData['nickname'])) {
                            $this->auth->getUser()->save(['nickname' => $extend['nickname'] . $this->auth->getUser()->id]);
                        }
                        //油桶编号
                        $user_id=$this->auth->getUser()->id;
                        $extend['oil_num']=1000+$user_id;
                        $this->auth->getUser()->save(['oil_num' => $extend['oil_num']]);
//                        if($extend['oil_num']){
//                            //生成油桶编号
//                            $user_id=$this->auth->getUser()->id;
//                            if($user_id>999999){
//                                $this->auth->getUser()->save(['oil_num' => $extend['oil_num'] . $user_id]);
//                            }else{
//                                $this->auth->getUser()->save(['oil_num' => $extend['oil_num'] . str_pad($user_id, 6, '0', STR_PAD_LEFT)]);
//                            }
//                        }
                        //设置队id
                        if($pid>0){
                            //获取父级的队id
                            $pdid=UserModel::where('id',$pid)->value('did');
                            $player=UserModel::where('id',$pid)->value('layer');
                            $this->auth->getUser()->save(['layer'=>$player+1,'did' => $pdid]);
                        }else{
                            //层数是0 .父级id是0的队id是自己 -这种的是自动团队长，又改为手动团队长。did=0
                            $this->auth->getUser()->save(['layer'=>0]);
                        }
                    }
                    $oauthData['user_id'] = $this->auth->getUser()->id;
                    $oauthData['createtime'] = time();
                    UserOauth::strict(false)->insert($oauthData);
                } else {
                    // 找到第三方登录信息，直接登录
                    $user_id = $userOauth->user_id;
                    if ($user_id && $this->auth->direct($user_id) && $this->auth->getUser()) {       // 获取到用户
                        $oauthData['logincount'] = $userOauth->logincount + 1;
                        $oauthData['logintime'] = time();
                        $userOauth->allowField(true)->save($oauthData);
                    } else {         // 用户已被删除 重新执行登录
                        // throw \Exception('此用户已删除');
                        $userOauth->delete();
                        $this->oauthLoginOrRegisterOrBindOrRefresh($event, $decryptData, $platform, $provider);                    }
                }
                break;
            case 'refresh':
                if (!$userOauth) {
                    throw \Exception('未找到第三方授权账户');
                }
                if (!empty($oauthData['nickname'])) {
                    $refreshFields['nickname'] = $oauthData['nickname'];
                }
                if (!empty($oauthData['headimgurl'])) {
                    $refreshFields['avatar'] = $oauthData['headimgurl'];
                }
                $this->auth->getUser()->save($refreshFields);
                $userOauth->allowField(true)->save($oauthData);
                break;
            case 'bind':
                if (!$this->auth->getUser()) {
                    throw \Exception('请先登录');
                }

                $oauthData['user_id'] = $this->auth->getUser()->id;

                if ($userOauth) {
                    if ($userOauth['user_id'] != 0 && $userOauth['user_id'] != $this->auth->getUser()->id && UserModel::get($userOauth['user_id'])) {
                        throw \Exception('该账号已被其他用户绑定');
                    }
                    $oauthData['id'] = $userOauth->id;
                    $userOauth->strict(false)->update($oauthData);
                } else {
                    $oauthData['logincount'] = 1;
                    $oauthData['logintime'] = time();
                    $oauthData['createtime'] = time();
                    UserOauth::strict(false)->insert($oauthData);
                }
                break;
        }
        if ($this->auth->getUser()) {
            $this->setUserVerification($this->auth->getUser(), $provider, $platform);
            return $this->auth->getToken();
        }
        return false;
    }

    /**
     * 第三方用户授权信息
     */
    public function thirdOauthInfo()
    {
        $user = $this->auth->getUser();
        $platform = request()->header('platform');
        $userOauth = UserOauth::where([
            'platform' => $platform,
            'user_id'  => $user->id
        ])->field('headimgurl, nickname')->find();
        $this->success('获取成功', $userOauth);
    }


    /**
     * 解除绑定
     */
    public function unbindThirdOauth()
    {
        $user = $this->auth->getUser();
        $platform = $this->request->post('platform');
        $provider = $this->request->post('provider');

        $verification = $user->verification;
        if (!$verification->mobile) {
            $this->error('请先绑定手机号再进行解绑操作');
        }

        $verifyField = $platform;
        if ($platform === 'App' && $provider === 'Wechat') {
            $verifyField = 'wxOpenPlatform';
        }

        $verification->$verifyField = 0;
        $user->verification = $verification;
        $user->save();
        $userOauth = UserOauth::where([
            'platform' => $platform,
            'provider'  => $provider,
            'user_id' => $user->id
        ])->delete();
        if ($userOauth) {
            $this->success('解绑成功');
        }
        $this->error('解绑失败');
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        if ($this->auth->isLogin()) {
            $this->auth->logout();
        }
        $this->success(__('Logout successful'));
    }

    /**
     * 注销账号
     */
    public function delete()
    {
        //$this->auth->setAllowFields(['id', 'username', 'nickname', 'mobile', 'avatar', 'score', 'money', 'commission']);
        $user = $this->auth->getUser();
        $user_data = UserModel::where('id',$user->id)->find();
        if($user_data){
            if($user_data['money']>0 || $user_data['commission']>0){
                $this->error('您的余额未清0，注销失败');
            }
        }
        //$this->auth->delete($user->id);
        //注销后保留油桶号，其他手机号，Op信息清空
        UserModel::where('id',$user->id)->update(['mobile'=>'']);
        // 删除token信息
        Db::name('user_token')->where('user_id', $user->id)->delete();

        UserOauth::where('user_id', $user->id)->delete();

        $this->success('注销成功');
    }
    /**
     * 修改会员个人信息
     *
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $birthday 生日
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio', '');
        $birthday = $this->request->post('birthday');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $user->nickname = $nickname;
        }
        if ($bio) {
            $user->bio = $bio;
        }
        if ($birthday) {
            $user->birthday = $birthday;
        }
        if (!empty($avatar)) {
            $user->avatar = $avatar;
        }
        $user->save();
        $this->success();
    }

    private function getUserDefaultFields()
    {
        $userConfig = json_decode(\addons\sum\model\Config::get(['name' => 'user'])->value, true);
        return $userConfig;
    }

    private function setUserVerification($user, $provider, $platform)
    {
        $verification = $user->verification;
        if ($platform === 'App') {
            $platform = '';
            if ($provider === 'Wechat') {
                $platform = 'wxOpenPlatform';
            } elseif ($provider === 'Alipay') {
                $platform = 'aliOpenPlatform';
            }
        }
        if ($platform !== '') {
            $verification->$platform = 1;
            $user->verification = $verification;
            $user->save();
        }
    }

    /**
     * 绑定解绑-解绑推荐人
     */
    public function unbindTj(){
        $user = $this->auth->getUser();
        //判断下边是否有人xj=下级
        $xj_count=UserModel::where('pid',$user['id'])->count();
        if($xj_count>0){
            $this->success("因有下级团队不能解绑，只能注销账户。",1);
        }
        // 断链 pid=0  去除团队 did=0
        UserModel::where('id',$user['id'])->update(['pid'=>0,'did'=>0]);
        $this->success('操作成功');
    }
    /**
     * 绑定解绑-绑定推荐人
     */
    public function bindTj(){
        $user = $this->auth->getUserinfo();
        if($user['pid']>0){
            $this->error('你已有邀请人');
        }
        if($user['is_team_leader']==1){
            $this->error('尊敬的队长，您无须绑定！');
        }
        $to_user_num = $this->request->post('to_user_num');
        $to_user=UserModel::field("id,oil_num,mobile,pid,did")->where('oil_num',$to_user_num)->whereOr('mobile',$to_user_num)->find();
        if(!$to_user){
            $this->error('没有该用户',$to_user_num);
        }
        if($to_user['id']==$user['id']){
            $this->error('不能绑定该用户');
        }

        UserModel::where('id',$user['id'])->update(['pid'=>$to_user['id'],'did'=>$to_user['did']]);
        // 如何在解绑或自然进入期间 又邀请其他人，则其他人也跟着他进团队
        $user=UserModel::where('id',$user['id'])->find();//重新获取一下
        // 递归处理团队团队id
        $this->handleTeam($user['id'],$user['did']);
        $this->success('操作成功');
    }
    //处理团队id
    public function handleTeam($ids,$did){
        UserModel::where('id','in',$ids)->update(['did'=>$did]);
        $child_ids=UserModel::where('pid','in',$ids)->column('id');
        if($child_ids){
            $this->handleTeam($child_ids,$did);
        }
    }


}
